package com.campus.counseling.service.impl;

import com.campus.counseling.service.LSTMAnalysisService;
import com.campus.counseling.service.DL4JModelService;
import com.campus.counseling.service.EmotionDictionary;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.List;
import org.nd4j.linalg.api.ndarray.INDArray;

@Slf4j
@Service
@RequiredArgsConstructor
public class LSTMAnalysisServiceImpl implements LSTMAnalysisService {
    
    // 注入DL4J模型服务
    private final DL4JModelService dl4jModelService;
    // 注入情感词典
    private final EmotionDictionary emotionDictionary;
    
    // LSTM和情感词典的权重
    private static final double LSTM_WEIGHT = 0.5;  // 改为0.5
    private static final double EMOTION_WEIGHT = 0.5;  // 改为0.5
    
    @Override
    public BigDecimal analyzeChatContent(List<String> texts) {
        try {
            // 将文本列表中的文本合并成一个字符串
            String combinedText = String.join(" ", texts);
            log.info("开始分析聊天内容: length={}, content={}", combinedText.length(), combinedText);
            
            // 1. LSTM模型分析
            INDArray features = dl4jModelService.extractFeatures(texts);
            INDArray predictions = dl4jModelService.predict(features);
            double lstmScore = predictions.getDouble(0);
            
            // 2. 情感词典分析
            double emotionScore = emotionDictionary.calculateEmotionScore(combinedText);
            log.info("情感词典分析得分: {}", emotionScore);
            
            // 3. 根据情感词典分数决定是否反转LSTM分数
            if (emotionScore > 0.7) {  // 如果情感词典判定为高风险
                // 保持原值
                log.info("LSTM模型预测得分: {} (保持原值)", lstmScore);
            } else {
                // 反转
                lstmScore = 1.0 - lstmScore;
                log.info("LSTM模型预测得分: {} (已反转)", lstmScore);
            }
            
            // 4. 加权融合
            double finalScore = lstmScore * LSTM_WEIGHT + emotionScore * EMOTION_WEIGHT;
            log.info("加权融合计算: {} * {} + {} * {} = {}", 
                lstmScore, LSTM_WEIGHT, emotionScore, EMOTION_WEIGHT, finalScore);
            
            return BigDecimal.valueOf(finalScore).setScale(4, RoundingMode.HALF_UP);
        } catch (Exception e) {
            log.error("聊天内容分析失败", e);
            throw new RuntimeException("分析失败", e);
        }
    }

}